package com.qs.mall.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qs.mall.controller.api.ProductFeignClient;
import com.qs.mall.dto.Product;
import com.qs.mall.entity.Order;
import com.qs.mall.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RequestMapping(value = "/order")
@RestController
//@DefaultProperties(defaultFallback = "orderFallback")  //可以在类上指定默认熔断降级方法
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 通过RestTemplate远程调用order-service获取到商品信息，创建订单。
     */
    @PostMapping("/{id}")
    public String order(@PathVariable Long id) {
        //提供RestTemplate调用商品微服务
        Product product = restTemplate.getForObject("http://localhost:9002/product/" + id, Product.class);
        logger.info("获取到商品：{}", product);
        logger.info("开始下订单。。。");
        Order order = new Order();
        order.setId(1L);
        order.setPrice(product.getPrice());
        order.setNumber(1);
        order.setProductId(product.getId());
        order.setProductName(product.getProductName());
        order.setUserId("000014");
        order.setUsername("张三");
        orderService.save(order);
        logger.info("订单创建成功");
        return "操作成功";
    }


    @GetMapping("/{id}")
    @HystrixCommand(fallbackMethod = "orderFallback", commandProperties= {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="5000")})
    public Product getOrder(@PathVariable Long id) {
        logger.info("使用rest访问。。。");
        //可以直接使用服务名代替服务提供应用的ip
        return restTemplate.getForObject("http://product-service/product/" + id, Product.class);
    }

    //定义服务降级方法，在服务调用失败时会调用该方法
    public Product orderFallback(Long id){
        logger.info("服务降级，调用默认的返回方法");
        Product product = new Product();
        product.setProductDesc("熔断：触发默认的降级方法");
        return product;
    }


    @GetMapping("/buy/{id}")
    public Product getOrderByFeign(@PathVariable Long id) {
        logger.info("使用feign优雅调用商品服务。。");
        return productFeignClient.findById(id);
    }

}
